package com.ruoyi.room.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.dto.RoomThreeDTO;
import com.ruoyi.pojo.*;
import com.ruoyi.room.service.*;
import com.ruoyi.vo.RoomPageBuildVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bxl
 * 标题： xxx接口
 */
@RestController
@RequestMapping("/Common/")
/*
 * TODO
 *   1.公共接口
 * */
@Slf4j
public class CommonController {
    @Autowired
    ITbBuildingRoomService buildingroomService;
    @Autowired
    ITbBuildingService buildingService;
    @Autowired
    ITbBuildingblockService buildingblockService;
    @Autowired
    ITbUnitService unitService;
    @Autowired
    ITbFloorService floorService;
    @Autowired
    ITbRoomService roomService;
    /*
          TODO
               1.处理elementUi 树形结构返回数据
                 一级根节点为 当前小区
                    二级根节点为 各个楼栋
                      三级根节点为 各个单元
                          四级根节点各个楼层
                             五级根节点为 各个房间 （显示房间一组）
               2.构建树形结构数据      disabled: true禁用   false启用
               3.:default-expanded-keys="[2, 3]"
                   作用：默认展开指定节点。
                   说明：设置初始状态下哪些节点是展开的。这里的 [2, 3] 表示 ID 为 2 和 3 的节点将默认展开。
                   示例： 如果树结构中有 ID 为 2 和 3 的节点，它们将默认展开。
                 :default-checked-keys="[5]"
                   作用：默认选中指定节点。
                   说明：设置初始状态下哪些节点是选中的。这里的 [5] 表示 ID 为 5 的节点将默认选中。
                   示例： 如果树结构中有 ID 为 5 的节点，它将默认被选中。
       */
    //树形结构
    @GetMapping("getThree")
    public AjaxResult getThree(Integer id) {//校区id
        //树形结构
        List<RoomThreeDTO> li =new ArrayList<>();
        List<String> expanded = new ArrayList<>();//默认展开的节点
        List<String> checked = new ArrayList<>();//默认选中的节点
        //1.封装小区
        TbBuilding building = buildingService.getById(id);
        RoomThreeDTO roomThreeDTO = new RoomThreeDTO();
        roomThreeDTO.setId(building.getBuildingId()+"");
        roomThreeDTO.setDisabled(false);
        roomThreeDTO.setLabel(building.getBuildingName());

        //2.封装楼栋   roomThreeDTO.setChildren();
        //查询当前所有楼栋
        List<TbBuildingblock> buildingblockList = buildingblockService.list();
         List<RoomThreeDTO> buildingblocks = new ArrayList<>();//并将楼栋封装成集合存入到roomThreeDTO.setChildren();
        for (TbBuildingblock buildingblock : buildingblockList) {
            RoomThreeDTO buildingblockThree = new RoomThreeDTO();
            buildingblockThree.setId(building.getBuildingId()+"-"+buildingblock.getId()+"-");
            buildingblockThree.setDisabled(false);
            buildingblockThree.setLabel(buildingblock.getBlockNumber());
            buildingblocks.add(buildingblockThree);//存储楼栋到小区的setChildren中
        }

        //3.封装单元
         //查询出所有的单元
        List<TbUnit> unitList =   unitService.list();//查询出所有单元
        for (RoomThreeDTO buildingblock : buildingblocks) {
            List<RoomThreeDTO> units = new ArrayList<>();//用来存储所有单元集合并存放到楼栋的setChildren中
            for (TbUnit tbUnit : unitList) {
                RoomThreeDTO unitThree = new RoomThreeDTO();
                unitThree.setId(buildingblock.getId()+tbUnit.getId()+"-");
                unitThree.setDisabled(false);
                unitThree.setLabel(tbUnit.getUnitNumber());
                units.add(unitThree);
                //4.封装楼层
                //查询出所有楼层
                List<TbFloor> floorList = floorService.list();
                List<RoomThreeDTO> floors = new ArrayList<>();//用来存储所有楼层集合并存放到单元的setChildren中
                for (TbFloor tbFloor : floorList) {
                    RoomThreeDTO floorThree = new RoomThreeDTO();
                    floorThree.setId(unitThree.getId()+tbFloor.getId()+"-");
                    floorThree.setDisabled(false);
                    floorThree.setLabel(tbFloor.getFloorNumber()+"");

                    //查询所有房间
                    List<TbRoom> rooms = roomService.list();
                    List<RoomThreeDTO> roomsThree = new ArrayList<>();
                    for (TbRoom room : rooms) {
                        RoomThreeDTO roomThreeDTO1 = new RoomThreeDTO();
                        roomThreeDTO1.setId(floorThree.getId()+room.getId());
                        //TODO  在这个处理回显
                       List<TbBuildingRoom> romH =  roomService.getAll(id);
                        for (TbBuildingRoom h : romH) {
                            String str = h.getBuildingId()+"-"+h.getBuildingblockId()+"-"+h.getUnitId()+"-"+h.getFloorId()+"-"+h.getRoomId();
                            if (str.equals(roomThreeDTO1.getId())){//处理回显
                                    expanded.add(floorThree.getId());
                                    checked.add(roomThreeDTO1.getId());
                                    roomThreeDTO1.setDisabled(false);
                            }else{
                                roomThreeDTO1.setDisabled(true);
                            }
                        }
                        roomThreeDTO1.setLabel(room.getRoomNumber());
                        roomsThree.add(roomThreeDTO1);
                    }
                    floorThree.setChildren(roomsThree);
                    floors.add(floorThree);
                }
                unitThree.setChildren(floors);//把单元存入到楼层
            }
            buildingblock.setChildren(units);
        }

        //判断Children要存放的集合不为空才可存
        if (buildingblocks.size()>0){
            roomThreeDTO.setChildren(buildingblocks);
        }
        li.add(roomThreeDTO);
        Map map = new HashMap<>();
        map.put("li",li);
        map.put("expandedKeys", expanded);
        map.put("checkedKeys", checked);
        return AjaxResult.success(map);
    }


    //统计信息
    @GetMapping("getCount")
    public AjaxResult getCount(Integer id) {
        //获取小区信息
        TbBuilding building = buildingService.getById(id);
        //查询出总户数，入住户数，待住户数
        LambdaQueryWrapper<TbBuilding> qw = new LambdaQueryWrapper<>();
        qw.eq(TbBuilding::getBuildingId, building.getBuildingId());
        String address = buildingService.getOne(qw).getBuildingName();
        List<Map<String, Object>> mapList = buildingroomService.findCount(id);
        Integer ru = 0;
        Integer wei = 0;
        Integer count = 0;
        for (Map<String, Object> map : mapList) {
            ru += convertToInt(map.get("blockRu"));
            wei += convertToInt(map.get("blockWei"));
            count += convertToInt(map.get("countAll"));
        }
        System.out.println("----------------------");
        //查询出小区总人数
        List<String> list = buildingroomService.findUserId(1);
        //用户id
        List<Integer> list1 = new ArrayList<>();
        list.stream().forEach(item -> {
            String[] split = item.split(",");
            list1.addAll(Arrays.stream(split)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList()));
        });
        Map map = Map.of("address", address, "ru", ru, "wei", wei, "count", count, "userCount", list1.size());
        return AjaxResult.success(map);
    }


    // 辅助方法：将对象转换为整数
    private int convertToInt(Object obj) {
        if (obj instanceof Integer) {
            return (Integer) obj;
        } else if (obj instanceof String) {
            try {
                return Integer.parseInt((String) obj);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("无法将字符串转换为整数: " + obj);
            }
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal) obj).intValue();
        } else if (obj instanceof Number) {
            return ((Number) obj).intValue();
        } else {
            throw new IllegalArgumentException("对象不是有效的数字: " + obj);
        }
    }
}
